﻿using System;
using System.Threading.Tasks;
using System.Xml;
using TIBCO.Rendezvous;
using static Org.BouncyCastle.Math.EC.ECCurve;

namespace HamcoWcs.Tools.Tibco
{
    public class VirtualTibcoServer
    {
        public TibcoConfiguration Config { get; set; }

        public NetTransport Transport { get; set; }


        public Queue Queue { get; set; }
        public Listener Listener { get; set; }
        public VirtualTibcoServer(TibcoConfiguration config,NetTransport transport  )
        {
            Config = config;
            Transport = transport;

            this.Queue = Queue.Default;
            this.Listener = new Listener(Queue, VirtualReceiveHandler, Transport, Config.SendSubject, null);

            Task.Run(async () =>
            {
                while (true)
                {
                    Queue.Dispatch();
                    await Task.Delay(50);
                }
            });
        }

        /// <summary>接收MES数据处理</summary>
        private void VirtualReceiveHandler(object listener, MessageReceivedEventArgs messageReceivedEventArgs)
        {
            string content = messageReceivedEventArgs.Message.GetField(Config.SendField).Value.ToString() ?? "";

            var messageName = XmlHelper.GetMessageName(content).ToUpper();
            if (string.IsNullOrEmpty(messageName)) return;
            //messageName = messageName.Replace("Request", "Reply");

            content = XmlHelper.SetReplyMessageName(content);
            var message = new Message() { SendSubject = Config.RecvSubject };
            message.AddField(Config.SendField, content);
            this.Transport.Send(message);
        }

        public static void DoVirtualReply(string messageName, string message, Action<string> doReply)
        {
            switch (messageName)
            {
                case "AREYOUTHEREREQUEST":
                case "MACHINEMODECHANGEREQUEST":
                case "CHANGEMACHINEPALLETTYPEREQUEST":
                case "PALLETANDBOXASSIGNREQUEST":
                case "VALIDATEPALLETINPUTREQUEST":
                case "VALIDATEPALLETLISTREQUEST":
                case "INVENTORYPALLETDATAREQUEST":
                case "INVENTORYZONEDATAREQUEST":
                    doReply?.Invoke(message);
                    break;
                default:
                    break;
            }
        }
    }
}
